﻿package com.projects.xenia.prompts_activities;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.UUID;

import com.projects.xenia.Documents_Return;
import com.projects.xenia.R;
import com.projects.xenia.R.drawable;
import com.projects.xenia.R.id;
import com.projects.xenia.R.layout;
import com.projects.xenia.global_modules.MainGlobalModule;
import com.projects.xenia.ref_classes.GoodsRefItem;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.InputType;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;

public class Activity_ReturnGoodsPrompt extends Activity {
	
	private Bundle DocExtras;
	
	private Documents_Return DocumentClass;
	
	private Button Prompt_Numeric_One;
	private Button Prompt_Numeric_Two;
	private Button Prompt_Numeric_Three;
	private Button Prompt_Numeric_Four;
	private Button Prompt_Numeric_Five;
	private Button Prompt_Numeric_Six;
	private Button Prompt_Numeric_Seven;
	private Button Prompt_Numeric_Eight;
	private Button Prompt_Numeric_Nine;
	private Button Prompt_Numeric_Null;	
	private Button Prompt_Numeric_Point;
	private Button Prompt_Numeric_Enter;
	private Button Prompt_Numeric_Clear;	
	private Button Prompt_Numeric_BackSpace;
	
	private TextView ReturnGoodsDescrTextView;
	private ImageView ReturnPromptGoodsImageImageView;
	
	private Button ReturnBaseDateButton;
	private TextView ReturnValueTextView;
	private Button ReturnBaseButton;
	private TextView CounterTextView;
	
	
	private static Context Ctx;
	
	private Button ReturnGoodsMeasuresButton;
	
	private static final int IDD_ReturnBaseDialog = 0;
	private static final int IDD_ReturnMeasureDialog = 1;
	private static final int IDD_ReturnDateDialog = 2;
	private static final int IDD_MeasuresDialog = 3;
	private static final int IDD_ValidationDialog = 4;
	
	
	private Cursor MeasuresCursor;
	private Cursor ReturnBaseCursor;
	private boolean FormUpdated = false;
	
	
	private String [] Date_Types = new String [] {"Изготовлен:","Годен до:"};
	
	int GoodsRefPosition;
	
	Drawable Img;
	
	protected Cursor GetMeasuresCursor () {
		return (MainGlobalModule.DBE.rawQuery("select a.id as _id,   b.descr || '(' || a.mul || ')' as descr ,  a.mul as mul , b.descr as odescr from xref_goodsmeasures a left outer join xref_Measures b on a.measures_id = b.id where a.goods_id = ? order by a.mul asc", new String [] {DocumentClass.Line.goods_id}));		
	}
	
	private void RefreshMeasuresCursor () {
		
		try {
			Cursor ScalarCursor = MainGlobalModule.DBE.query ("xenum_ReturnBases", new String []{"descr"}, "id = ?", new String []{DocumentClass.Line.goods_measures_id}, null, null, null);
			ScalarCursor.moveToFirst();
			ReturnBaseButton.setText(ScalarCursor.getString(0));
		} catch (Exception e) {
			ReturnBaseButton.setText ("");
		}
		
	}
	
	protected Cursor GetReturnBasesCursor () {
		return (MainGlobalModule.DBE.rawQuery("select id as _id, descr as descr from xenum_ReturnBases order by descr", null));		
	}
	
	private void RefreshReturnBaseButton () {
		
		try {
			Cursor ScalarCursor = MainGlobalModule.DBE.query ("xenum_returnbases", new String []{"descr"}, "id = ?", new String []{DocumentClass.Line.return_base}, null, null, null);
			ScalarCursor.moveToFirst();
			ReturnBaseButton.setText(ScalarCursor.getString(0));
		} catch (Exception e) {
			ReturnBaseButton.setText ("");
		}
		
	}
	
	
	private void SetDateTypeTextView () {
		CounterTextView.setText(Date_Types[DocumentClass.Line.date_type]);	
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) < Configuration.SCREENLAYOUT_SIZE_LARGE) {			
			setTheme(android.R.style.Theme_NoTitleBar_Fullscreen);			
		}
		
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);            
	    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
	    
	    setContentView(R.layout.prompt_return_goods);
	    
	    Ctx = this;
	    
	    DocumentClass = (Documents_Return) MainGlobalModule.DocumentClass;
	    
	    if (getIntent().getExtras()!=null) {
	    	GoodsRefItem GoodsItem = MainGlobalModule.GoodsRef.get(getIntent().getExtras().getInt("GoodsRefPosition"));
	    	DocumentClass.SetLineDocByKey(GoodsItem, DocumentClass.Line.return_base, DocumentClass.Line.create_date);
	    }
	    
		ReturnGoodsDescrTextView = (TextView) findViewById(R.id.ReturnPrompt_GoodsDescr);
		ReturnGoodsDescrTextView.setText(DocumentClass.Line.goods_descr);
		MeasuresCursor = GetMeasuresCursor();		
		
		
		ReturnBaseCursor = GetReturnBasesCursor();
		ReturnBaseButton = (Button) findViewById(R.id.ReturnBaseButton);
		ReturnBaseButton.setOnClickListener(ReturnBaseDialog);
		RefreshReturnBaseButton ();		
		
		ReturnBaseDateButton = (Button) findViewById(R.id.ReturnDate);		
		ReturnBaseDateButton.setText(MainGlobalModule.FormatDate(DocumentClass.Line.create_date));		
		ReturnBaseDateButton.setOnClickListener(ReturnDateDialog);
		
		ReturnGoodsMeasuresButton = (Button) findViewById(R.id.ReturnPrompt_ReturnMeasures);
		ReturnGoodsMeasuresButton.setOnClickListener(ReturnGoodsMeasuresButton_Click);
		ReturnGoodsMeasuresButton.setText(String.format("%s(%.1f)",DocumentClass.Line.goods_measures_descr,DocumentClass.Line.factor));
		
		
        Prompt_Numeric_One = (Button)findViewById(R.id.ReturnPrompt_One);
        Prompt_Numeric_One.setOnClickListener(Prompt_Numeric_Number_Click);

        Prompt_Numeric_Two = (Button)findViewById(R.id.ReturnPrompt_Two);
        Prompt_Numeric_Two.setOnClickListener(Prompt_Numeric_Number_Click);

        Prompt_Numeric_Three = (Button)findViewById(R.id.ReturnPrompt_Three);
        Prompt_Numeric_Three.setOnClickListener(Prompt_Numeric_Number_Click);

        Prompt_Numeric_Four = (Button)findViewById(R.id.ReturnPrompt_Four);
        Prompt_Numeric_Four.setOnClickListener(Prompt_Numeric_Number_Click);

        Prompt_Numeric_Five = (Button)findViewById(R.id.ReturnPrompt_Five);
        Prompt_Numeric_Five.setOnClickListener(Prompt_Numeric_Number_Click);

        Prompt_Numeric_Six = (Button)findViewById(R.id.ReturnPrompt_Six);
        Prompt_Numeric_Six.setOnClickListener(Prompt_Numeric_Number_Click);

        Prompt_Numeric_Seven = (Button)findViewById(R.id.ReturnPrompt_Seven);
        Prompt_Numeric_Seven.setOnClickListener(Prompt_Numeric_Number_Click);

        Prompt_Numeric_Eight = (Button)findViewById(R.id.ReturnPrompt_Eight);
        Prompt_Numeric_Eight.setOnClickListener(Prompt_Numeric_Number_Click);

        Prompt_Numeric_Nine = (Button)findViewById(R.id.ReturnPrompt_Nine);
        Prompt_Numeric_Nine.setOnClickListener(Prompt_Numeric_Number_Click);

        Prompt_Numeric_Null = (Button)findViewById(R.id.ReturnPrompt_Null);
        Prompt_Numeric_Null.setOnClickListener(Prompt_Numeric_Number_Click);
        
        Prompt_Numeric_Point = (Button)findViewById(R.id.ReturnPrompt_Point);
        Prompt_Numeric_Point.setOnClickListener(Prompt_Numeric_Number_Point); 
        
        Prompt_Numeric_Clear = (Button)findViewById(R.id.ReturnPrompt_Clear);
        Prompt_Numeric_Clear.setOnClickListener(Prompt_Numeric_Clear_Click);

        Prompt_Numeric_BackSpace = (Button)findViewById(R.id.ReturnPrompt_BackSpace);
        Prompt_Numeric_BackSpace.setOnClickListener(Prompt_Numeric_BackSpace_Click);
        
        Prompt_Numeric_Enter = (Button)findViewById(R.id.ReturnPrompt_Enter);
        Prompt_Numeric_Enter.setOnClickListener(Prompt_Numeric_Enter_Click);		

        ReturnValueTextView = (TextView)findViewById(R.id.ReturnPrompt_Return);        
        ReturnValueTextView.setSelectAllOnFocus(true);        
                        
        ReturnValueTextView.setText(String.valueOf(DocumentClass.Line.return_value));
        ReturnValueTextView.setInputType(InputType.TYPE_NULL);
        ReturnValueTextView.setSelected(true);
        ReturnValueTextView.requestFocus();        
        
        ReturnPromptGoodsImageImageView = (ImageView)findViewById(R.id.ReturnPrompt_GoodsImage);
        
        CounterTextView = (TextView)findViewById(R.id.CounterTextView);
        SetDateTypeTextView ();        
        
        new Thread(new Runnable() {
            public void run() {
         	   
         	    File ImgPath = new File (String.format("%s/%s.jpg", MainGlobalModule.GoodsImagesPath,DocumentClass.Line.goods_id));
         	    
           	 		if (ImgPath.exists()) {
           	 			Img = Drawable.createFromPath(ImgPath.getAbsolutePath());
           	 			ReturnPromptGoodsImageImageView.post(new Runnable() {
               	 			public void run() {                    	 
               	 			ReturnPromptGoodsImageImageView.setImageDrawable(Img);
               	 		ReturnPromptGoodsImageImageView.setAdjustViewBounds(true);
               	 			}});		
           	 		}
           	 		else
           	 		{
           	 		ReturnPromptGoodsImageImageView.post(new Runnable() {
               	 			public void run() {                    	 
               	 			ReturnPromptGoodsImageImageView.setImageResource(R.drawable.st_photos);
               	 			ReturnPromptGoodsImageImageView.setAdjustViewBounds(true);
               	 			}});
           	 		}
        		
           	 	
             	}           
     	}).start();	
		
        
	}
	
	private OnClickListener ReturnGoodsMeasuresButton_Click = new OnClickListener() {
		@Override
		public void onClick(View v) {
		
			showDialog (IDD_MeasuresDialog);			
			
		}
	};
	
	private OnClickListener ReturnBaseDialog = new OnClickListener() {		
		@Override
		public void onClick(View v) {
			showDialog(IDD_ReturnBaseDialog);			
		}
	};
	
	private OnClickListener ReturnDateDialog = new OnClickListener() {		
		@Override
		public void onClick(View v) {
			
			AlertDialog.Builder adb = new AlertDialog.Builder(Ctx);			
			adb.setItems(Date_Types,Date_TypesDialog);
			adb.create().show();	
						
		}
	};
	
	private DialogInterface.OnClickListener Date_TypesDialog = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			DocumentClass.Line.date_type = which;
			SetDateTypeTextView ();
			ShowDateDialog ();
		}
	};
	
	private void ShowDateDialog () {
		showDialog(IDD_ReturnDateDialog);
	}
	
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);
		
		switch (id) {
		
		case IDD_ReturnDateDialog:			
						
			Calendar PromptCalendar = Calendar.getInstance();			
			if (DocumentClass.Line.create_date!=null) {
				PromptCalendar.setTime(DocumentClass.Line.create_date);
			}
			
			((DatePickerDialog)dialog).updateDate(PromptCalendar.get(Calendar.YEAR), PromptCalendar.get(Calendar.MONTH),PromptCalendar.get(Calendar.DAY_OF_MONTH));		
			
			break;
		}		
		
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {		
			
			super.onCreateDialog(id);
				
			AlertDialog.Builder adb = new AlertDialog.Builder(this);
			
			switch (id) {

			case IDD_ReturnBaseDialog:
				
				adb.setTitle("Основания возврата");
				adb.setCursor(ReturnBaseCursor, ReturnBaseDialogClickListener , "descr");
				return adb.create();
			
			case IDD_ReturnDateDialog:
				
				Calendar PromptCalendar = Calendar.getInstance();				
				if (DocumentClass.Line.create_date!=null) {
					PromptCalendar.setTime(DocumentClass.Line.create_date);
				}				
				return new DatePickerDialog(this, ReturnDateSetListener, PromptCalendar.get(Calendar.YEAR), PromptCalendar.get(Calendar.MONTH), PromptCalendar.get(Calendar.DAY_OF_MONTH));			
			
			case IDD_MeasuresDialog:
				adb.setTitle("Единицы");
				adb.setCursor(MeasuresCursor , ReturnPrompt_MeasuresDialogClickListener , "descr");
				return adb.create();
				
			case IDD_ValidationDialog:
				adb.setTitle("Ошибка");
				adb.setMessage("Не все поля заполнены !!!");
				return adb.create();
			
		}
			return null;
			
	};
	
	private DialogInterface.OnClickListener ReturnPrompt_MeasuresDialogClickListener = new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
	    	FormUpdated = true;
	    	MeasuresCursor.moveToPosition(which);
	    	DocumentClass.Line.goods_measures_id = MeasuresCursor.getString(0);
	    	DocumentClass.Line.goods_measures_descr = MeasuresCursor.getString(3);
	    	DocumentClass.Line.factor = MeasuresCursor.getInt(2);
	    	ReturnGoodsMeasuresButton.setText(MeasuresCursor.getString(1));
		}
	};	
	
	private DialogInterface.OnClickListener ReturnBaseDialogClickListener = new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
	    	FormUpdated = true;
	    	ReturnBaseCursor.moveToPosition(which);
	    	DocumentClass.Line.return_base = ReturnBaseCursor.getString(0);
	    	DocumentClass.Line.return_base_descr = ReturnBaseCursor.getString(1);	    	
	    	ReturnBaseButton.setText(ReturnBaseCursor.getString(1));	    	
	    }		
	};
	
	private OnDateSetListener ReturnDateSetListener = new OnDateSetListener() {		
		@Override
		public void onDateSet(DatePicker view, int year, int month,int day) {
			FormUpdated = true;
			Calendar PromptCalendar = Calendar.getInstance();			
			//PromptCalendar.set(year,month,day,0,0,0);
			DocumentClass.Line.create_date = new GregorianCalendar(year, month, day, 0, 0, 0).getTime();
			ReturnBaseDateButton.setText(MainGlobalModule.FormatDate(DocumentClass.Line.create_date));	
		}
	};	

	private OnClickListener Prompt_Numeric_Number_Click = new OnClickListener() {
		@Override
		public void onClick(View v) {

			Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			vb.vibrate(30);

			Button NumberButton = (Button)v;
			String NumberButtonText = (String) NumberButton.getText();

			String FocusedTextViewText = (String) ReturnValueTextView.getText().toString();			
			
			if (ReturnValueTextView.isSelected()) {
				FocusedTextViewText = "";
				ReturnValueTextView.setSelected(false);				
			}	
			
			if (FocusedTextViewText.equals("0")) {
				ReturnValueTextView.setText(NumberButtonText);
			}
			else {
				ReturnValueTextView.setText(FocusedTextViewText.concat(NumberButtonText));
			}
			
		}
	};
	
	private OnClickListener Prompt_Numeric_Number_Point = new OnClickListener() {
		@Override
		public void onClick(View v) {

			Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			vb.vibrate(30);

			Button NumberButton = (Button)v;
			String NumberButtonText = (String) NumberButton.getText();

			String FocusedTextViewText = (String) ReturnValueTextView.getText().toString();

			if (ReturnValueTextView.isSelected()) {
				FocusedTextViewText = "0.";
				ReturnValueTextView.setSelected(false);	
				return;
			}	
			
			if (FocusedTextViewText.contains(".")!=true) {
				ReturnValueTextView.setText(FocusedTextViewText.concat(NumberButtonText));					
			}
			
		}
	};
	
	private OnClickListener Prompt_Numeric_Clear_Click = new OnClickListener() {
		@Override
		public void onClick(View v) {	
		
			ReturnValueTextView.setText("0");			
			
		}
	};
	
	private OnClickListener Prompt_Numeric_BackSpace_Click = new OnClickListener() {
		@Override
		public void onClick(View v) {	
			
			String FocusedTextViewText = ReturnValueTextView.getText().toString();
			
			if (ReturnValueTextView.isSelected()) {
				FocusedTextViewText = "";
				ReturnValueTextView.setSelected(false);
			}		
			
			if (FocusedTextViewText.length() > 1) {
				ReturnValueTextView.setText(FocusedTextViewText.substring(0, FocusedTextViewText.length()-1));	
			}
			else {
				ReturnValueTextView.setText("0");
			}			
			
		}
	};

	private OnClickListener Prompt_Numeric_Enter_Click = new OnClickListener() {
		@Override
		public void onClick(View v) {	
			
			if (DocumentClass.Line.return_base==null||DocumentClass.Line.create_date==null) {					
				showDialog(IDD_ValidationDialog);
				return;	
			}
			
			FormUpdated = true;
			SaveData();			
			FinishActivity ();
					
		}
	};
	
	private void FinishActivity () {
		
		Intent DataIntent = new Intent ();
		setResult(RESULT_OK, DataIntent);
		DataIntent.putExtra("GoodsRefPosition", GoodsRefPosition);		
		finish();
		
	}
	
	private void SaveData () {
		
		if (FormUpdated) {
		
			Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			vb.vibrate(30);			
			
			DocumentClass.Line.return_value = Double.parseDouble(ReturnValueTextView.getText().toString());
			DocumentClass.Line.return_sum = DocumentClass.Line.price*DocumentClass.Line.factor * DocumentClass.Line.return_value;
			DocumentClass.InsertUpdateLine();
			
		}
	
	}
	
}
